using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Npc : MonoBehaviour
{
    // Start is called before the first frame update
    private enum State
    {
        Idle,
        Attack,
        Walk
    };
    private State curState;
    public float runSpeed = 5f;
    public Transform target;
    public float FollowDistance;
    public float AttackDistance;
    public float attackRadius = 1f;
    public Transform attackPoint;

    private float Health = 100f;
    public Slider healthSlider;


    private CharacterController npc_controller;
    private Animator npc_animator;
    private void Awake()
    {
        curState = State.Idle;
        npc_animator = GetComponent<Animator>();
        npc_controller = GetComponent<CharacterController>();
        healthSlider.value = Health * 0.01f;
    }

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        npc_controller.checkGround();
        float distance = Vector3.Distance(target.transform.position, transform.position);
        if (distance < AttackDistance)
        {
            curState = State.Attack;
            npc_animator.SetTrigger("Attack");
        }
        else if (distance < FollowDistance)
        {
            curState = State.Walk;
            npc_animator.SetBool("IsWalk", true);
        }
        else
        {
            curState = State.Idle;
            npc_animator.SetBool("IsWalk", false);
        }
        walk();
    }

    private void walk()
    {
        if (!npc_controller.isGrounded())
        {
            npc_animator.SetBool("IsWalk", false);
            return;
        }
        float move_direction = target.position.x - transform.position.x;
        if (move_direction < 0)
        {
            if (transform.localScale.x > 0f)
                transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
        }
        if (move_direction > 0)
        {
            if (transform.localScale.x < 0f)
                transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
        }
        if (curState == State.Walk)
        {
            if (move_direction < 0)
            {
                npc_controller.Move(-1f * new Vector3(runSpeed, 0f, 0f));
            }
            else if (move_direction > 0)
            {
                npc_controller.Move(1f * new Vector3(runSpeed, 0f, 0f));

            }
        }
    }
    public void Hurt(int damage)
    {
        npc_animator.SetTrigger("Hurt");
        curState = State.Idle;
        Health -= damage;
        if (Health <= 0)
        {
            Health = 0;
        }
        healthSlider.value = Health * 0.01f;
    }




}
